import { DownloadOutlined, PauseCircleFilled, PlayCircleFilled } from '@ant-design/icons';
import { Button, Checkbox, List, message, PageHeader, Skeleton, Tabs, Tag, Tooltip } from 'antd';
import useRouter from 'hooks/use-router';
import React, { useMemo, useState, useRef, useEffect } from 'react';
import { useWebSocket } from 'ahooks';
import './index.less';
import Config from 'common/config';
import { download } from 'utils/httpUtils';
import dayjs from 'dayjs';
import { saveAs }  from 'file-saver';
import Axios from 'axios';

const logOptions = ['教师', '评测', '识别', '手指', '翻书', '人像'];
const colorMap: any = {
    right: 'green',
    wrong: 'red',
    skip: 'blue',
};
export default (props: any) => {
    const router = useRouter();
    const { deviceId, userRemark, deviceModel, status, version } = router.location.state as any;
    const [logChecked, setLogChecked] = useState([...logOptions]);
    const [messageHistory, setMessageHistory] = useState<any>([]);
    const [imageBookData, setImageBookData] = useState({
        word: '',
        book: '',
        page: '',
        sentence: '',
    });
    const audioRef: any = useRef();
    const imageRef: any = useRef();
    const [currentPlayAudio, setCurrentPlayAudio] = useState({
        url: '',
    });
    const { sendMessage } = useWebSocket(Config.WS_URL, {
        onMessage: (message: any) => {
            try {
                message = JSON.parse(message?.data);
            } catch (e) {
                console.error(e);
            }
            // 根据类型将消息数据存入 messageHistory.current 对应的属性中，UI 从对应属性取数据
            switch (message.messageType) {
                case 'ping': {
                    sendMessage?.(
                        JSON.stringify({
                            messageType: 'ping',
                            deviceId: deviceId,
                        }),
                    );
                }
                default:
                    break;
            }
            const logTypeMap: any = {
                dialogManage: '教师',
                openPage: '翻书',
                distinguish: '识别',
                pointPage: '手指',
                evaluation: '评测',
                person: '人像'
            };
            switch (message.logType) {
                case 'dialogManage':
                case 'openPage':
                case 'distinguish':
                case 'pointPage':
                case 'evaluation':
                    console.log(message);
                    setMessageHistory((prev: any) => {
                        return [
                            {
                                ...message,
                                type: logTypeMap[message.logType],
                            },
                            ...prev,
                        ];
                    });
                    break;
                case 'bookImage':
                    imageRef.current.src = 'data:image/jpeg;base64,' + message.image;
                    break;
                case 'bookImageData':
                    setImageBookData(message);
                    break;
            }
        },
    });

    const logList = useMemo(() => {
        return messageHistory.filter((item: any) => logChecked.indexOf(item.type) > -1);
    }, [logChecked, messageHistory]);

    useEffect(() => {}, []);
    /** 远程升级 */
    const remoteUpgrade = () => {
        sendMessage?.('升级');
        message.success('远程升级');
    };
    /** 关机 */
    const shutdown = () => {
        message.success('关机');
    };
    const logCheckedChange = (list: any[]) => {
        setLogChecked(list);
    };

    /** 播放 */
    const playAudio = (record: any) => {
        setCurrentPlayAudio({
            url: record.audioUrl,
        });
        audioRef.current.src = record.audioUrl;
        audioRef.current.oncanplay = () => {
            audioRef.current.play();
        };
        audioRef.current.onended = () => {
            setCurrentPlayAudio({
                url: ''
            })
        }
    };
    /** 暂停 */
    const pauseAudio = (record: any) => {
        setCurrentPlayAudio({
            url: '',
        });
    };
    /** 下载 */
    const download = (record: any) => {
        Axios.get(window.location.origin + record.audioUrl, {
            responseType: 'blob'
        }).then((res) => {
            saveAs(res.data, record.startTime)
        })
    };

    return (
        <div className="real-time">
            <header className="header">
                <PageHeader
                    title="机器人实时"
                    subTitle={`${deviceId}-${userRemark}-${deviceModel}   版本号 ${version}`}
                    tags={status === 'online' ? <Tag color="green">在线</Tag> : <Tag color="red">离线</Tag>}
                    extra={[
                        <Button disabled key={1} type="primary" onClick={remoteUpgrade}>
                            远程升级
                        </Button>,
                        <Button disabled key={2} type="primary" onClick={shutdown}>
                            关机
                        </Button>,
                    ]}
                    onBack={() => router.push('/monitor')}
                />
            </header>
            <main className="main">
                <div className="left">
                    <Tabs>
                        <Tabs.TabPane tab="课本摄像头" key="book">
                            <img
                                ref={imageRef}
                                className="mb20"
                                src={require('assets/images/test.jpg')}
                                style={{ width: '100%' }}
                            />
                        </Tabs.TabPane>
                        <Tabs.TabPane disabled tab="人脸摄像头" key="human">
                            <img width="100%" alt="" />
                        </Tabs.TabPane>
                    </Tabs>
                    <div className="info">
                        <label>书本状态</label>
                        <div>{imageBookData.page}页</div>
                        <label>手指状态</label>
                        <div>
                            {imageBookData.sentence ? (
                                <span>[句子]{imageBookData.sentence}</span>
                            ) : (
                                <span>[单词]{imageBookData.word}</span>
                            )}
                        </div>
                        {/* <label>肢体状态</label>
                        <div>趴着</div>
                        <label>学习状态</label>
                        <div>开心</div> */}
                    </div>
                    <audio className="audio-player" controls></audio>
                </div>
                <div className="right">
                    <div>
                        <Checkbox.Group options={logOptions} value={logChecked} onChange={logCheckedChange} />
                    </div>
                    <List
                        dataSource={logList}
                        style={{ height: 'calc(100vh - 100px)', overflowY: 'auto' }}
                        renderItem={(item: any) => (
                            <List.Item
                                actions={
                                    ['教师', '评测', '识别'].indexOf(item.type) > -1
                                        ? [
                                              currentPlayAudio.url !== item.audioUrl && (
                                                  <PlayCircleFilled onClick={() => playAudio(item)} />
                                              ),
                                              currentPlayAudio.url === item.audioUrl && (
                                                  <PauseCircleFilled onClick={() => pauseAudio(item)} />
                                              ),
                                              <DownloadOutlined onClick={() => download(item)} />,
                                          ]
                                        : []
                                }
                            >
                                <Skeleton title={false} loading={false} active>
                                    <List.Item.Meta
                                        title={
                                            <div>
                                                {dayjs(item.startTime).format('HH:mm:ss')} {item.type}
                                            </div>
                                        }
                                        description={
                                            <div>
                                                {item.type === '评测' && (
                                                    <div>
                                                        <span className="bold mr5">[{item.type}]</span>
                                                        {item.evaluationResult === 'right' ? (
                                                            <span>{item.evaluationContent}</span>
                                                        ) : (
                                                            <>
                                                                <span style={{ color: 'red', marginRight: 5 }}>
                                                                    {item.evaluationContent}:
                                                                </span>
                                                                {item.evaluationDetails.map((word: any) => (
                                                                    <Tooltip title={word.score}>
                                                                        <span
                                                                            style={{
                                                                                marginRight: 5,
                                                                                color: colorMap[word.result],
                                                                            }}
                                                                        >
                                                                            {word.content}
                                                                        </span>
                                                                    </Tooltip>
                                                                ))}
                                                            </>
                                                        )}
                                                    </div>
                                                )}
                                                {item.type !== '评测' && (
                                                    <div>
                                                        <span className="bold mr5">[{item.type}]</span>
                                                        {item.sentenceContent || item.wordContent}
                                                    </div>
                                                )}
                                            </div>
                                        }
                                    />
                                </Skeleton>
                            </List.Item>
                        )}
                    />
                </div>
            </main>
            <audio ref={audioRef} controls style={{ display: 'none' }} />
        </div>
    );
};
